import { Modal } from "antd";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router";
import { Image } from "antd";
import { useRecoilState, useRecoilValue } from "recoil";
import { inviteExam, register } from "../api";
import FormInformation from "../component/formInformation.component";
import { REGISTER_FORM } from "../constants/common";
import { formValidation } from "../data/formValidation";
import Team from "../image/Team.png";
import {
  ItemsTypeArray,
  IChangedValuesType,
  IRegisterFormProps,
  IUserInfo,
  IError,
  ISiteInfo,
} from "../interface/index";
import { basicInfoState } from "../recoil/atoms/infoFormAtoms";
import { siteInfo } from "../recoil/atoms/siteInfo";

function Information() {
  const [disable, setDisable] = useState<boolean>(true);
  const [basicInfo, setBasicInfo] = useRecoilState<IRegisterFormProps>(basicInfoState);
  const siteBasicInfo = useRecoilValue<ISiteInfo>(siteInfo);  // 从 recoil 状态中拿到 网站信息
  const navigate = useNavigate();

  const onFinish = () => {
    register(basicInfo)
      .then((userInfo: IUserInfo) => {
        sessionStorage.setItem("userId", userInfo.id || "");
        inviteExam(userInfo.id, basicInfo.job ?? "")
          .then((inviteId: string) => {
            success(inviteId);
          })
          .catch((err: IError) => {
            error(err.message);
          });
      })
      .catch((err: IError) => {
        error(err.message);
      });
  };

  const onValuesChange = (
    changedValues: IChangedValuesType,
    allValues: IRegisterFormProps
  ) => {
    setBasicInfo(allValues);
  };

  useEffect(() => {
    const valueObject: string[] = [];
    if (!basicInfo || Object.values(basicInfo).some((item) => !item)) return;
    formValidation.forEach((item: ItemsTypeArray) => {
      Object.keys(basicInfo).forEach((key: string) => {
        if (
          item.name == key &&
          item.rule[1].pattern.test(basicInfo[key as REGISTER_FORM])
        ) {
          valueObject.push(key);
        }
      });
      valueObject.length === formValidation.length
        ? setDisable(false)
        : setDisable(true);
    });
  }, [formValidation, basicInfo]);

  function success(data: string) {
    Modal.success({
      title: "信息输入成功！",
      content: (
        <div>
          <p>即将进入面试题, 祝您好运!</p>
        </div>
      ),
      onOk() {
        navigate(`test?inviteId=${data}`);
      },
    });
  }

  function error(msg: string) {
    Modal.error({
      title: "信息输入失败！",
      content: (
        <div>
          <p>{msg}</p>
        </div>
      ),
    });
  }

  return (
    <div className="w-full h-full flex justify-center items-center bg-[url('../image/bgd.png')] bg-no-repeat bg-cover">
      <div
        className="bg-white lg:w-1/2 lg:h-3/5 w-4/5 h-4/5 p-10 rounded-3xl relative bg-[url('../image/login.png')] bg-no-repeat bg-cover shadow-xl flex justify-around items-center"
      >
        <div className="text-xl text-white font-bold absolute sm:left-12 -top-12 sm:text-sky-500 sm:top-12 sm:text-2xl">
          {siteBasicInfo.companyName}
        </div>
        <div className="lg:flex w-full h-auto justify-center items-center">
          <div className="lg:w-3/5 flex justify-center items-center">
            <Image width={'100%'} preview={false} src={Team} />
          </div>
          <FormInformation
            onFinish={onFinish}
            formValidation={formValidation}
            labelCol={4}
            onValuesChange={onValuesChange}
            wrapperCol={14}
            disable={disable}
          />
        </div>
      </div>
    </div>
  );
}

export default Information;
